#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>

#include "config/config.h"
#include "content.h"

#include "serveur.h"
#include "gerer_client.h"
#include "traitement.h"


void
gerer_requete(int indice)
{
  char *requete = recupere_requete(sock_tab[i]);
  if (requete == NULL)
    {
      return NULL;
    }
  

  requete_t req = traiter_requete(requete);
  free(requete);
  requete = NULL;
  char *mauvaise_requete = "bad request";

  
  if (req->User_Agent)
    {
      log_clients[i].user_agent = malloc(sizeof(char)*(strlen(req->User_Agent)+1));
      strcpy(log_clients[i].user_agent,req->User_Agent);
    }
 

  if (req->methode > -1)
    {
      
      char *meth;
      switch(req->methode)
	{
	case 0:
	  meth = "GET";
	  break;
	case 1:
	  meth = "HEAD";
	  break;
	default:
	  meth = "POST";
	  break;
	}

      log_clients[i].requete = malloc(sizeof(char)*(strlen(meth)+strlen(req->url_demande)+2));
      sprintf(log_clients[i].requete,"%s %s",meth,req->url_demande);

      get_page(sock_tab[i],req,&log_clients[i]);
    }
  else
    {
      log_clients[i].requete= malloc(sizeof(char)*(strlen(mauvaise_requete)+1));
      strcpy(log_clients[i].requete,mauvaise_requete);
      
      envoyer_code(sock_tab[i],requete_mauvaise,&log_clients[i],BAD_REQUEST);
      
      int fd = open(BAD_REQUEST, O_RDONLY);
      perror_and_exit_whenever(fd == -1);
      copier_fichier(sock_tab[i],fd);
      close(fd);
    }



liberer_requete(req);
return
}
